<template>
  <div class="online-report">
    <div class="search-from">
      <!-- 查询条件 -begin -->
      <div v-if="configQueryList && configQueryList.length > 0">
        <el-collapse v-model="queryPanel" accordion @change="onQueryAreaSwitch">
          <el-collapse-item name="1" title="点击展开显示查询信息">
            <div>
              <el-form
                ref="queryForm"
                class="search-from-el-form"
                :label-position="'left'"
                :inline="true"
                :model="queryInfo"
                @keydown.native.enter.prevent="doReportQuery()"
              >
                <el-form-item v-for="(item, index) in configQueryList" :key="index" :index="index">
                  <template slot="label">
                    <div :title="getQueryItemLabel(item)" class="ellipsis">{{ getQueryItemLabel(item) + ':' }}</div>
                  </template>
                  <!-- 日期选择器 yyyy-MM-dd HH:mm:ss -->
                  <template v-if="item.type=='date'">
                    <el-row v-if="item.mode==2">
                      <el-col :span="11">
                        <el-date-picker
                          :ref="item.key+'_begin'"
                          v-model="queryInfo['onlyshow_'+item.key+'_begin']"
                          :format="item.format"
                          :placeholder="'请选择起始值'"
                          :transfer="true"
                          :type="item.realType"
                          size="small"
                          :value-format="item.format"
                          @change="(str)=>handleQueryDateChange(str, item.key+'_begin')"
                        />
                      </el-col>
                      <el-col :span="2" style="text-align: center">&nbsp;~</el-col>
                      <el-col :span="11">
                        <el-date-picker
                          :ref="item.key+'_end'"
                          v-model="queryInfo['onlyshow_'+item.key+'_end']"
                          :format="item.format"
                          :placeholder="'请选择结束值'"
                          :transfer="true"
                          :type="item.realType"
                          size="small"
                          :value-format="item.format"
                          @change="(str)=>handleQueryDateChange(str, item.key+'_end')"
                        />
                      </el-col>
                    </el-row>
                    <el-date-picker
                      v-else
                      :ref="item.key"
                      v-model="queryInfo['onlyshow_'+item.key]"
                      :format="item.format"
                      :placeholder="'请选择'+item.title"
                      :transfer="true"
                      :type="item.realType"
                      size="small"
                      :value-format="item.format"
                      @change="(str)=>handleQueryDateChange(str, item.key)"
                    />
                  </template>

                  <!-- 时间选择器 HH:mm:ss -->
                  <template v-else-if="item.type=='time'">
                    <el-row v-if="item.mode==2">
                      <el-col :span="11">
                        <el-date-picker
                          :ref="item.key+'_begin'"
                          v-model="queryInfo['onlyshow_'+item.key+'_begin']"
                          :format="item.format"
                          :placeholder="'请选择起始值'"
                          :transfer="true"
                          size="small"
                          :value-format="item.format"
                          type="datetime"
                          @change="(str)=>handleQueryDateChange(str, item.key+'_begin')"
                        />
                      </el-col>
                      <el-col :span="2" style="text-align: center">&nbsp;~</el-col>
                      <el-col :span="11">
                        <el-date-picker
                          :ref="item.key+'_end'"
                          v-model="queryInfo['onlyshow_'+item.key+'_end']"
                          :format="item.format"
                          :placeholder="'请选择结束值'"
                          :transfer="true"
                          size="small"
                          :value-format="item.format"
                          type="datetime"
                          @change="(str)=>handleQueryDateChange(str, item.key+'_end')"
                        />
                      </el-col>
                    </el-row>
                    <el-date-picker
                      v-else
                      :ref="item.key"
                      v-model="queryInfo['onlyshow_'+item.key]"
                      :format="item.format"
                      :placeholder="'请选择'+item.title"
                      :time-picker-options="{disabledHours:true}"
                      :transfer="true"
                      size="small"
                      :type="item.realType"
                      :value-format="item.format"
                      @change="(str)=>handleQueryDateChange(str, item.key)"
                    />
                  </template>

                  <!-- 下拉树 -->
                  <template v-else-if="item.mode==6">
                    <filter-select-cascader
                      :ref="item.key"
                      :is-multiple="true"
                      :props="{ checkStrictly: true }"
                      :remote-url="() => {
                        return loadTree(item.loadTree)
                      }"
                      :type="'cascader'"
                      @change="(str)=>handleQueryTreeChange(str, item.key)"
                    />
                  </template>

                  <!-- 自定义下拉框 -->
                  <template v-else-if="item.mode==7">
                    <el-select
                      :ref="item.key"
                      v-model="queryInfo[item.key]"
                      :placeholder="'请选择'+item.title"
                      :transfer="true"
                      size="small"
                      clearable
                    >
                      <el-option
                        v-for="(dict, dIndex) in item.dictList"
                        :key="dIndex"
                        :index="index"
                        :label="dict.label"
                        :value="dict.value"
                      >{{ dict.text }}
                      </el-option>
                    </el-select>
                  </template>

                  <template v-else>
                    <template v-if="item.dictList && item.dictList.length>0 && (item.mode==4 ||item.mode==3)">
                      <!-- 多选 -->
                      <el-select
                        v-if="item.mode==3"
                        v-model="queryInfo['onlyshow_'+item.key]"
                        :index="index"
                        clearable
                        multiple
                        size="small"
                        @change="(str)=>handleDictMultipleOk(str, item.key)"
                      >
                        <el-option
                          v-for="(dict, dIndex) in item.dictList"
                          :key="dIndex"
                          :index="index"
                          :label="dict.label"
                          :value="dict.value"
                        >{{ dict.text }}
                        </el-option>
                      </el-select>

                      <!-- 单选 -->
                      <el-select v-if="item.mode==4" v-model="queryInfo[item.key]" size="small" clearable>
                        <el-option
                          v-for="(dict, dIndex) in item.dictList"
                          :key="dIndex"
                          :index="index"
                          :label="dict.label"
                          :value="dict.value"
                        >{{ dict.text }}
                        </el-option>
                      </el-select>
                    </template>

                    <!-- 数值查询 -->
                    <template v-else-if="item.type=='number'">
                      <el-row v-if="item.mode==2">
                        <el-col :span="11">
                          <el-input-number
                            :ref="item.key+'_begin'"
                            v-model="queryInfo[item.key+'_begin']"
                            :placeholder="'请输入起始值'"
                            size="small"
                            clearable
                            style="width: 100%"
                          />
                        </el-col>
                        <el-col :span="2" style="text-align: center">&nbsp;~</el-col>
                        <el-col :span="11">
                          <el-input-number
                            :ref="item.key+'_end'"
                            v-model="queryInfo[item.key+'_end']"
                            :placeholder="'请输入结束值'"
                            clearable
                            size="small"
                            style="width: 100%"
                          />
                        </el-col>
                      </el-row>
                      <el-input-number
                        v-else
                        :ref="item.key"
                        v-model="queryInfo[item.key]"
                        clearable
                        size="small"
                        placeholder="'请输入'+item.title"
                        style="width: 100%"
                      />
                    </template>

                    <!-- 默认输入框 模糊查询参数加* -->
                    <template v-else>
                      <el-input
                        v-if="item.mode==5"
                        :ref="item.key"
                        v-model="queryInfo['onlyshow_'+item.key]"
                        :placeholder="'请输入'+item.title"
                        clearable
                        size="small"
                        @input="(e)=>handleLikeQueryChange(e, item.key)"
                      />
                      <el-input
                        v-else
                        :ref="item.key"
                        v-model="queryInfo[item.key]"
                        size="small"
                        :placeholder="'请输入'+item.title"
                        clearable
                      />
                    </template>
                  </template>
                </el-form-item>
              </el-form>
              <el-row :span="24">
                <el-col>
                  <el-button icon="ios-search-outline" type="primary" plain size="mini" @click="formReportQuery()">查询</el-button>
                  <el-button icon="ios-redo-outline" style="margin-left: 8px" plain size="mini" type="warning" @click="resetReportQuery">重置</el-button>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 查询条件 -end -->
    </div>
    <div class="table-content">
      <div class="table-operation">
        <el-dropdown @command="handleOperationClick">
          <el-button type="warning" size="mini">
            更多操作<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="exportPdf">导出pdf</el-dropdown-item>
            <el-dropdown-item command="exportExcel">导出excel</el-dropdown-item>
            <el-dropdown-item command="printPdf">预览打印PDF</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="table-list">
        <el-table :key="key" :data="tableData" highlight-current-row max-height="600" stripe style="width: 100%">
          <el-table-column
            v-for="head in formThead"
            :key="head.fieldName"
            :label="head.fieldText"
            :prop="head.fieldName"
            show-overflow-tooltip
          />
        </el-table>
        <div class="table-pagination">
          <el-pagination
            :current-page="pageNo"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, sizes, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            @prev-click="handlePrevClick"
            @next-click="handleNextClick"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {
  checkParam,
  excelView,
  exportExcel,
  exportPdf,
  getQueryInfo,
  httpApi,
  loadTableHead,
  verification
} from '@/api/jimu'
import FilterSelectCascader from '@/components/FilterSelectCascader'
import { ajaxFileDownload2 } from '@/components/tool'

export default {
  name: 'OnlineReport',
  components: { FilterSelectCascader },
  props: {
    configReportId: {
      type: [String, Number],
      require: true,
      default: ''
    }
  },
  data: function() {
    return {
      reportId: '',
      loadDataNow: true,
      isRpFirstLoad: true,
      queryPanel: '',
      enhanceFunction: '',
      loading: false,
      visible: false,
      reportParamList: [],
      reportParamObj: {},
      callback: '',
      configQueryList: [],
      tokenKey: 'X-Access-Token',
      jmSheettokenXxxTest: '',
      queryInfo: {},
      timerArr: [],
      lock: '',
      lockVisible: false,
      lockLoading: false,
      viewData: {},
      queryResultData: {},
      returnPreviousPage: false,
      rpBar: true,
      jimuReportName: '',
      dbCode: '',
      tenantId: '',
      excelConfigId: '',
      token: '',
      directDownload: true,
      dictInfo: [],
      reportName: '',
      reportMode: '',
      shareView: '',
      pageSize: 10,
      pageNo: 1,
      total: 0,
      props: {
        label: 'label',
        value: 'value',
        children: 'children'
      },
      tableData: [],
      key: 1, // table key
      formThead: []
    }
  },
  watch: {
    queryInfo: {
      deep: true,
      handler() {
        Object.keys(this.queryInfo).map(key => {
          const tempstr = this.queryInfo[key]
          if (tempstr && typeof tempstr === 'string') {
            this.queryInfo[key] = tempstr
          }
        }
        )
      }
    }
  },
  mounted() {
    this.reportId = this.configReportId
    if (!this.reportId) {
      this.$message.error('请传入正确的报表ID')
      this.goBack()
      return
    }
    this.initLoad()
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    async loadTree(loadTreeUrl) {
      let data = {
        data: []
      }
      await httpApi(loadTreeUrl).then(res => {
        data = {
          data: this.buildTree(res.data)
        }
      })
      return data
    },
    buildTree(array) {
      const tree = []
      const map = new Map()

      array.forEach(item => {
        item.label = item.title
        map.set(item.id, item)
      })
      array.forEach(item => {
        const parent = map.get(item.pid)
        if (parent) {
          (parent.children || (parent.children = [])).push(map.get(item.id))
        } else {
          tree.push(map.get(item.id))
        }
      })

      console.log(JSON.stringify(tree))
      return tree
    },
    getShareViewUrl(excelConfigId, callback) {
      if (this.shareView === '1') {
        const config = localStorage.getItem(excelConfigId)
        const param = {}
        param.reportId = excelConfigId
        if (config) {
          param.lock = config
        }
        verification(param).then(res => {
          callback(res.result)
        })
      } else {
        callback('0')
      }
    },
    handleReportQueryInfo(token) {
      return new Promise(resolve => {
        this.configQueryList = []
        this.queryInfo = {}
        const requestParam = this.getRequestUrlParam()
        getQueryInfo({
          'reportId': this.reportId,
          'param': JSON.stringify(requestParam)
        }).then(result => {
          if (!result) {
            resolve()
            return
          }
          const ls = result.list
          if (ls) {
            const { list, queryInfo } = this.getFirstQueryInfo(ls)
            this.configQueryList = [...list]
            this.queryInfo = queryInfo
          }
          const jsStr = result.jsStr
          if (jsStr) {
            // eslint-disable-next-line no-eval
            this.enhanceFunction = eval('(' + jsStr + ')')
            this.executeEnhanceJs()
          } else {
            this.enhanceFunction = ''
          }
          if (result.rpName) {
            this.reportName = result.rpName
            document.title = result.rpName + ' - \u79ef\u6728\u62a5\u8868, \u514d\u8d39\u7684\u53ef\u89c6\u5316\u62a5\u8868\uff01'
            this.jimuReportName = result.rpName
          }
          resolve()
        })
      }
      )
    },
    initLoad(excelConfigId) {
      const _that = this
      const token = this.getRequestUrlParam().token
      if (token && token != null && token != '') {
        window.localStorage.setItem('JmReport-Access-Token', token)
      }
      this.token = window.localStorage.getItem('JmReport-Access-Token')
      this.excelConfigId = excelConfigId
      const pageSize = this.getRequestUrlParam().pageSize
      if (pageSize) {
        this.pageSize = pageSize
      }
      const requestParam = this.getRequestUrlParam()
      this.handleReportQueryInfo(token).then(async() => {
        let page = 1
        const exportDefaultValue = {}
        // 初始化表头
        await loadTableHead({ reportId: this.reportId }).then(res => {
          _that.formThead = res
          _that.dbCode = res[0]['dbCode']
        })
        var loadExcelView = function(inputparam) {
          const requestUrlParam = _that.getRequestUrlParam()
          if (inputparam) {
            Object.keys(inputparam).map(key => {
              requestParam[key] = inputparam[key]
              exportDefaultValue[key] = inputparam[key]
              if (key == 'pageNo') {
                page = Number(inputparam[key])
              }
            }
            )
          } else if (requestUrlParam) {
            Object.keys(requestUrlParam).map(key => {
              if (key == 'pageNo') {
                page = Number(requestUrlParam[key]) > 1 ? Number(requestUrlParam[key]) : page
              }
            }
            )
          }
          if (!requestParam.pageNo) {
            requestParam.pageNo = page
          }
          _that.query2RequestParam(_that.queryInfo, requestParam)
          _that.getShareViewUrl(excelConfigId, result => {
            if (result == '0') {
              const requestParamObj = _that.getRequestUrlParam()
              if (_that.loadDataNow) {
                requestParam['jmViewFirstLoad'] = '1'
                _that.doReportQuery(requestParam)
              } else {
                _that.queryPanel = '1'
              }
              let requestStr = ``
              if (requestParamObj) {
                for (const key in requestParamObj) {
                  requestStr += (requestStr.includes('?') ? `&` : `?`) + `${key}=${requestParamObj[key]}`
                }
                requestStr += (requestStr.includes('?') ? `&` : `?`) + `token=${token}`
              }
            } else if (result == '1') {
              _that.$message.error({
                content: '\u8be5\u94fe\u63a5\u5df2\u5931\u6548\uff01',
                duration: 3
              })
            } else if (result == '2') {
            } else if (result == '3') {
              _that.$message.error({
                content: '\u8be5\u94fe\u63a5\u4e0d\u5b58\u5728\uff01',
                duration: 3
              })
            } else if (result == 'noExist') {
              _that.$message.error({
                content: '\u8be5\u62a5\u8868\u5df2\u88ab\u5220\u9664\uff01',
                duration: 3
              })
            }
          }
          )
        }
        checkParam(_that.reportId).then(result => {
          if (!result) {
            result = []
          }
          const requestUrlParam = _that.getRequestUrlParam()
          const dbParam = {}
          if (result) {
            for (const item of result) {
              dbParam[item.paramName] = item.paramValue
            }
          }
          const inputparam = Object.assign(dbParam, requestUrlParam)
          loadExcelView(inputparam)
        })
      })
    },
    exportToExcel() {
      let dataStr = ''
      const queryParam = this.getRpQueryParam()

      queryParam.pageNo = this.pageNo
      queryParam.pageSize = this.pageSize
      queryParam['currentPageNo'] = this.pageNo
      queryParam['currentPageSize'] = this.pageSize
      queryParam['bigDataMode'] = true
      dataStr = JSON.stringify({
        excelConfigId: this.reportId,
        queryParam: queryParam
      })
      exportExcel(dataStr)
        .then(response => response.blob())
        .then(result => {
          ajaxFileDownload2(result, this.jimuReportName + '.xlsx', true)
        })
        .catch(error => this.$message.error('导出失败！' + error))
    },
    exportPdf() {
      const queryParam = this.getRpQueryParam()
      queryParam.pageNo = this.pageNo + ''
      queryParam.pageSize = this.pageSize
      queryParam['currentPageNo'] = this.pageNo + ''
      queryParam['currentPageSize'] = this.pageSize
      const dataStr = JSON.stringify({
        excelConfigId: this.reportId,
        queryParam: queryParam
      })
      exportPdf(dataStr)
        .then(response => response.blob())
        .then(result => {
          ajaxFileDownload2(result, this.jimuReportName + '.pdf', true)
        })
        .catch(error => this.$message.error('导出失败！') + error)
    },
    printPdf() {
      const queryParam = this.getRpQueryParam()
      queryParam.pageNo = this.pageNo + ''
      queryParam.pageSize = this.pageSize
      queryParam['currentPageNo'] = this.pageNo + ''
      queryParam['currentPageSize'] = this.pageSize
      const dataStr = JSON.stringify({
        excelConfigId: this.reportId,
        queryParam: queryParam
      })
      exportPdf(dataStr)
        .then(response => response.blob())
        .then(result => {
          const fileURL = URL.createObjectURL(new Blob([result], {
            type: 'application/pdf;chartset=UTF-8'
          }))
          window.open(fileURL)
        })
        .catch(error => this.$message.error('预览失败！') + error)
    },
    handleOperationClick(e) {
      if (e === 'exportExcel') {
        this.exportToExcel()
      }
      if (e === 'exportPdf') {
        this.exportPdf()
      }
      if (e === 'printPdf') {
        this.printPdf()
      }
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.doReportQuery()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.doReportQuery()
    },
    handlePrevClick() {
      this.pageNo--
      this.doReportQuery()
    },
    handleNextClick() {
      this.pageNo++
      this.doReportQuery()
    },
    setArrayValue(prop, key, arr) {
      this.$set(this[prop], key, arr)
    },
    executeEnhanceJs() {
      const _that = this
      if (_that.enhanceFunction) {
        _that.enhanceFunction.call(this)
      }
    },
    getQueryItemLabel(item) {
      if (item.duplicate === true) {
        return item.title + '(' + item.dbText + ')'
      } else {
        return item.title
      }
    },
    resetQueryInfo() {
      Object.keys(this.queryInfo).map(k => {
        if (k != this.tokenKey) {
          const queryConfigArr = this.configQueryList.filter(i => {
            return i.key == k
          }
          )
          let defVal = ''
          if (queryConfigArr && queryConfigArr.length > 0) {
            if (queryConfigArr[0].defaultValue) {
              defVal = queryConfigArr[0].defaultValue.toString()
            } else {
              defVal = ''
            }
          }
          this.queryInfo[k] = defVal
        }
      }
      )
    },
    formReportQuery() {
      this.resetPageNo()
      this.doReportQuery()
    },
    resetPageNo() {
      this.pageNo = 1
    },
    resetReportQuery() {
      this.resetPageNo()
      this.resetQueryInfo()
      this.initQueryParams(this.token, () => {
        this.doReportQuery()
      }
      )
    },
    initQueryParams(token, callback) {
      this.queryInfo = {}
      const requestParam = this.getRequestUrlParam()
      getQueryInfo(
        {
          'reportId': this.reportId,
          'param': JSON.stringify(requestParam)
        }).then(result => {
        const ls = result.list
        if (ls) {
          const { list, queryInfo } = this.getFirstQueryInfo(ls)
          this.queryInfo = queryInfo
          this.configQueryList = [...list]
        }
        const jsStr = result.jsStr
        if (jsStr) {
          // eslint-disable-next-line no-eval
          this.enhanceFunction = eval('(' + jsStr + ')')
          this.executeEnhanceJs()
        } else {
          this.enhanceFunction = ''
        }
        callback()
      })
    },
    getRpQueryParam() {
      const requestParam = this.getRequestUrlParam()
      if (!requestParam['pageNo']) {
        requestParam['pageNo'] = 1
      }
      this.query2RequestParam(this.queryInfo, requestParam)
      if (this.isRpFirstLoad) {
        requestParam['jmViewFirstLoad'] = '1'
      }
      return requestParam
    },
    handleQueryDateChange(str, key) {
      this.queryInfo[key] = str
    },
    handleQueryTreeChange(arr, key) {
      if (!arr || arr.length === 0) {
        this.queryInfo[key] = ''
      } else {
        this.queryInfo[key] = arr.map(arr => arr[arr.length - 1]).join(',')
      }
    },
    handleLikeQueryChange(e, key) {
      const str = e
      console.log('handleLikeQueryChange', e, key)
      if (str === 0 || str === '0') {
        this.queryInfo[key] = '*' + str + '*'
      } else if (str) {
        this.queryInfo[key] = '*' + str + '*'
      } else {
        this.queryInfo[key] = ''
      }
    },
    onQueryAreaSwitch() {
    },
    saveQueryResultData(data) {
      if (data) {
        Object.keys(data).map(dbCode => {
          if (data[dbCode]) {
            const list = data[dbCode]['list']
            this.queryResultData[dbCode] = list
          }
        }
        )
      }
    },
    handleDictMultipleOk(str, key) {
      if (!str || str.length === 0) {
        this.queryInfo[key] = ''
      } else {
        this.queryInfo[key] = str.join(',')
      }
    },
    getRequestUrlParam() {
      var url = window.location.href
      var index = url.indexOf('?')
      var param = {}
      if (index > 0) {
        var strs = url.substring(index + 1)
        var array = strs.split('\x26')
        for (const a of array) {
          var temp = a.split('\x3d')
          param[temp[0]] = decodeURIComponent(temp[1])
        }
      }
      return param
    },
    getQueryDefaultValue(defaultValue, type) {
      if (defaultValue === 0) {
        if (type == 'number') {
          defaultValue = 0
        } else {
          defaultValue = '0'
        }
      } else if (!defaultValue) {
        defaultValue = ''
      }
      return defaultValue
    },
    handleConfigToQueryInfo(vo, queryInfo, defaultValue) {
      const _that = this
      const type = vo.type
      const mode = vo.mode
      const key = vo.key
      if (mode == 1) {
        if (type == 'date' || type == 'time') {
          if (defaultValue) {
            queryInfo['onlyshow_' + key] = this.getDateByStr(defaultValue, vo.format)
          }
        }
        queryInfo[key] = defaultValue
      } else if (mode == 2) {
        const arr = (defaultValue + '').split('|')
        if (arr) {
          if (arr.length > 0) {
            queryInfo[key + '_begin'] = arr[0].trim()
          }
          if (arr.length > 1) {
            queryInfo[key + '_end'] = arr[1].trim()
          } else {
            queryInfo[key + '_end'] = ''
          }
          if (type == 'date' || type == 'time') {
            if (arr.length > 0 && arr[0]) {
              queryInfo['onlyshow_' + key + '_begin'] = this.getDateByStr(arr[0], vo.format)
            }
            if (arr.length > 1 && arr[1]) {
              queryInfo['onlyshow_' + key + '_end'] = this.getDateByStr(arr[1], vo.format)
            }
          }
        }
      } else if (mode == 3) {
        const arr = (defaultValue + '').split(',')
        _that.setArrayValue('queryInfo', 'onlyshow_' + key, arr)
        queryInfo[key] = defaultValue
      } else if (mode == 4) {
        queryInfo[key] = defaultValue
        if (defaultValue) {
          vo.select = false
          vo.queryType = 1
        }
      } else if (mode == 5) {
        if (defaultValue && defaultValue.length > 0) {
          queryInfo[key] = '*' + defaultValue + '*'
        } else {
          queryInfo[key] = ''
        }
        queryInfo['onlyshow_' + key] = defaultValue
      } else {
        queryInfo[key] = defaultValue
        if ((type == 'date' || type == 'time') && defaultValue) {
          queryInfo['onlyshow_' + key] = this.getDateByStr(defaultValue, vo.format)
        }
      }
    },
    getSearchFormKey(vo) {
      let key = ''
      if (vo.paramSearch == true) {
        key = vo.name
      } else {
        key = vo.dbCode + '__' + vo.name
      }
      return key
    },
    getFirstQueryInfo(list) {
      const queryInfo = {}
      if (list) {
        for (const vo of list) {
          vo['key'] = this.getSearchFormKey(vo)
          const defaultValue = this.getQueryDefaultValue(vo.defaultValue, vo.type)
          this.handleConfigToQueryInfo(vo, queryInfo, defaultValue)
        }
      }
      return {
        list: list,
        queryInfo: queryInfo
      }
    },
    getDateByStr(str, format) {
      if (!str) {
        return ''
      }
      str = str.trim()
      const date = new Date()
      if (format == 'HH:mm') {
        const hour = str.substring(0, 2)
        date.setHours(hour)
        const mill = str.substring(3)
        date.setMinutes(mill)
      } else if (format == 'HH:mm:ss') {
        const hour = str.substring(0, 2)
        date.setHours(hour)
        const mill = str.substring(3, 5)
        date.setMinutes(mill)
        const sec = str.substring(6)
        date.setSeconds(sec)
      } else if (format == 'mm:ss') {
        const mill = str.substring(0, 2)
        date.setMinutes(mill)
        const sec = str.substring(3)
        date.setSeconds(sec)
      } else if (format == 'HH') {
        date.setHours(str)
      } else if (format == 'mm') {
        date.setMinutes(str)
      } else if (format == 'ss') {
        date.setSeconds(str)
      } else {
        return dayjs(str).toDate()
      }
      return date
    },
    query2RequestParam(queryInfo, requestParam) {
      Object.keys(queryInfo).map(key => {
        if (queryInfo[key] && !key.startsWith('onlyshow_')) {
          requestParam[key] = queryInfo[key]
        }
      }
      )
      requestParam.pageNo = this.pageNo
      requestParam.pageSize = this.pageSize
    },
    dealDataList(resultList) {
      if (Object.keys(resultList).length == 1) {
        const dataKey = Object.keys(resultList)[0]
        const dataObj = resultList[dataKey]
        if (!dataObj.isPage && dataObj.total > 1) {
          dataObj['isPage'] = '1'
        }
      }
      const dataList = JSON.parse(JSON.stringify(resultList))
      let count = 0
      const pageObj = {}
      Object.keys(dataList).forEach(key => {
        const dataObj = dataList[key]
        if (!dataObj) {
          return
        }
        Object.keys(dataObj).forEach(resultKey => {
          if (resultKey.endsWith('total')) {
            if (dataObj[`isPage`] == '1' && dataObj['list'].length > 0) {
              count = dataObj[`count`]
              pageObj[key] = dataObj['total']
            }
            delete dataObj['total']
            delete dataObj['count']
          }
        }
        )
      }
      )
      return {
        dataList,
        count,
        pageObj
      }
    },
    doReportQuery(requestParam) {
      if (!requestParam) {
        requestParam = this.getRpQueryParam()
      }
      excelView({
        'id': this.reportId,
        'apiUrl': '',
        'params': JSON.stringify(requestParam)
      }).then(result => {
        if (!requestParam) {
          this.saveQueryResultData(result.dataList)
        }
        const dataMap = result.dataList
        delete dataMap['expData']
        const dealDataList = this.dealDataList(dataMap)
        const dataList = dealDataList.dataList[this.dbCode].list
        this.total = dealDataList.count
        this.tableData = dataList
        if (this.isRpFirstLoad) {
          this.dictInfo = result.dictInfo
          this.isRpFirstLoad = false
        }
      })
    }
  }
}
</script>
<style>
.online-report {
  margin: auto;
}
.search-from {
  .search-from-el-form {
    display: flex;
    flex-wrap: wrap;
    gap: 2px;
    flex-direction: row;
    align-content: center;
    justify-content: flex-start;
  }
}
.table-content {
  .table-operation {
    margin: 10px;
    float: right;
  }
  .table-pagination {
    margin: 10px;
  }
}
</style>
